package com.hfjyz.examination.dao.impl;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.hfjyz.examination.dao.BaseDao;

public abstract class JpaBaseDaoImpl<T, PK extends Serializable> implements
		BaseDao<T, PK> {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	private Class<T> entityClazz;

	protected JpaBaseDaoImpl(Class<T> entityClazz) {
		this.entityClazz = entityClazz;
	}

	@SuppressWarnings("unchecked")
	@Override
	public PK add(T entity) throws Exception {
		log.debug(" add entity: " + entity);
		entityManager.persist(entity);
		return (PK) hibernateTemplate.save(entity);
	}

	@Override
	public void update(T entity) throws Exception {
		hibernateTemplate.update(entity);
	}

	@Override
	public void delete(T entity) throws Exception {
		hibernateTemplate.delete(entity);
	}

	@Override
	@SuppressWarnings("unchecked")
	public T get(PK pk) throws Exception {
		return (T) hibernateTemplate.get(entityClazz, pk);
	}

	private EntityManager entityManager;

	/**
	 * @return the entityManager
	 */
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * @param entityManager
	 *            the entityManager to set
	 */
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	private HibernateTemplate hibernateTemplate;

	/**
	 * @return the hibernateTemplate
	 */
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	/**
	 * @param hibernateTemplate
	 *            the hibernateTemplate to set
	 */
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

}
